/* Copyright 2007 Gearbox Software - http://www.gearboxsoft.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http:www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.*/
namespace GearBlog.Web.Controllers
{
	using Castle.Components.Validator;
	using Castle.MonoRail.ActiveRecordSupport;
	using Castle.MonoRail.Framework;
	using GearBlog.Web.Filters;
	using GearBlog.Web.Models;
	using GearBlog.Web.Utils;
	using NHibernate.Expression;

	/// <summary>
    /// Summary description for AdminController
    /// </summary>
    [ControllerDetails("User", Area="Admin")]
	[AuthenticationFilter(typeof(FormsAuthenticationAgent), "Admins")]
    [Layout("adminuser")]
    public class AdminUserController:ExtendedControllerBase
    {
        public void List()
        {
            PropertyBag["Users"] = User.FindAll(Order.Asc("UserName"));
        }
        
        public void Create()
        {
            PropertyBag["id"] = 0;
			
			if (GetCurrentUser()==null)
				PropertyBag["User"] = new User();

            PropertyBag["Roles"] = Role.FindAll();
        }
        public void Edit(int id)
        {
			if (GetCurrentUser() == null)
				PropertyBag["User"] = User.Find(id);

            PropertyBag["Roles"] = Role.FindAll();
        }
        public void Save([ARDataBind("User", AutoLoad = AutoLoadBehavior.NewInstanceIfInvalidKey,Expect="user.roles")] User user)
        {
            if (RedirectToReferrerOnError(user))
            {
                if (user.Id==0) user.SetPasswordHash();
                user.Save();
                Flash["message"] = "User saved successfully.";
                RedirectToAction("list");
            }
        }
        public void ChangePassword(int userId, string password, string confirmPassword)
        {
            User user = User.Find(userId);
            user.Password = password;
            user.ConfirmPassword = confirmPassword;
            if (RedirectToReferrerOnError(user))
            {
                user.SetPasswordHash();
                user.Save();
                Flash["message"] = "Password changed successfully.";
                RedirectToAction("list");
            }

        }
		private User GetCurrentUser()
		{
			if (PropertyBag["User"] != null)
				return (User)PropertyBag["User"];
			else
				return (User) Flash["User"];
		}
        private bool RedirectToReferrerOnError(User user)
        {
        	ValidatorRunner runner;
        	bool isValid = true;
			if (user.Id == 0)
				isValid = IsValid(user, out runner, RunWhen.Insert | RunWhen.Everytime);
			else
				isValid = IsValid(user, out runner);
			if (!isValid)
            {
                Flash["ErrorSummary"] = runner.GetErrorSummary(user);
                Flash["User"] = user;
                RedirectToReferrer();
                return false;
            }
            return true;
        }
		private bool RedirectToReferrerOnError(UserInviteTicket inviteTicket)
		{
			ValidatorRunner runner;
			if (!IsValid(inviteTicket, out runner))
			{
				Flash["ErrorSummary"] = runner.GetErrorSummary(inviteTicket);
				Flash["InviteForm"] = inviteTicket;
				RedirectToReferrer();
				return false;
			}
			return true;
		}
		
        public void ChangeEnableStatus(int id)
        {
            User user = User.Find(id);
            user.IsEnabled = !user.IsEnabled;
            user.Save();
			RedirectToReferrer();
		}

		#region Invitation Routine
		public void ShowInvite()
		{
			PropertyBag["InviteFormtype"] = typeof (UserInviteTicket);
		}
		public void SaveInvite([ARDataBind("InviteForm")] UserInviteTicket inviteTicket )
		{
			UserInviteTicket originalInviteTicket = UserInviteTicket.FindByEmail(inviteTicket.Email);

			if (originalInviteTicket != null)
			{
				//User already invited before, resend
				originalInviteTicket.SendInvitation(this);
				Flash["message"] = "Invitation was created before. Resend invitation letter.";
			}
			else
				if (RedirectToReferrerOnError((inviteTicket)))
				{
					inviteTicket.Save();
					inviteTicket.SendInvitation(this);
					Flash["message"] = "Invitation record created Invitation mail sent.";
				}

			RedirectToAction("list");
		}


		#endregion


	}
}